package com.ourfuture.junitdemo.demo17;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class UserDaoJdbcImpl implements UserDao {

	private Connection connection;

	public Connection getConnection() {
		return connection;
	}

	public void setConnection(Connection connection) {
		this.connection = connection;
	}

	@Override
	public long addUser(User user) {
		String sql = "insert into user values (?,?)";
		long returnId = 0;
		try {
			PreparedStatement pstmt = this.getConnection().prepareStatement(
					sql, Statement.RETURN_GENERATED_KEYS);
			pstmt.setLong(1, user.getId());
			pstmt.setString(2, user.getName());
			pstmt.execute();
			ResultSet rs = pstmt.getGeneratedKeys();
			while (rs.next()) {
				returnId = rs.getLong(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return returnId;
	}

	@Override
	public User getUserById(long id) {
		// TODO Auto-generated method stub
		String sql = "select * from user where id = " + id;
		User user = new User();
		try {
			Statement stmt = this.getConnection().createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			if (rs.next()) {
				user.setId(rs.getLong(1));
				user.setName(rs.getString(2));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return user;
	}

}
